<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 助手</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background-color: #ffffff;
            height: 100vh;
            display: flex;
            overflow: hidden;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 280px;
            background-color: #f8f9fa;
            border-right: 1px solid #e9ecef;
            display: flex;
            flex-direction: column;
            transition: transform 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            position: relative;
            z-index: 1000;
            will-change: transform;
        }

        .sidebar.collapsed {
            transform: translateX(-280px);
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .sidebar-header h2 {
            font-size: 18px;
            font-weight: 500;
            color: #333;
            margin: 0;
        }

        .header-buttons {
            display: flex;
            gap: 8px;
            align-items: center;
        }

        .new-chat-btn {
            padding: 8px 12px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            white-space: nowrap;
            transform: scale(1);
            will-change: transform, background-color;
        }

        .new-chat-btn:hover {
            background-color: #0056b3;
            transform: scale(1.02);
        }

        .new-chat-btn:active {
            transform: scale(0.98);
        }

        .delete-history-btn {
            background: none;
            border: 1px solid #dc3545;
            color: #dc3545;
            padding: 6px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            display: flex;
            align-items: center;
            justify-content: center;
            transform: scale(1);
            will-change: transform, background-color, color;
        }

        .delete-history-btn:hover {
            background-color: #dc3545;
            color: white;
            transform: scale(1.05);
        }

        .delete-history-btn:active {
            transform: scale(0.95);
        }

        .chat-history {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }

        .chat-item {
            padding: 12px 16px;
            margin-bottom: 8px;
            background-color: white;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            font-size: 14px;
            color: #333;
            transform: translateY(0);
            will-change: transform, background-color, border-color;
        }

        .chat-item:hover {
            background-color: #f0f7ff;
            border-color: #007bff;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.1);
        }

        .chat-item.active {
            background-color: #e3f2fd;
            border-color: #007bff;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 123, 255, 0.15);
        }

        .chat-item:active {
            transform: translateY(0);
        }

        /* 主内容区域 */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            position: relative;
            transition: margin-left 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: margin-left;
        }

        .main-content.expanded {
            margin-left: -280px;
        }

        /* 顶部工具栏 */
        .toolbar {
            display: flex;
            align-items: center;
            padding: 16px 20px;
            border-bottom: 1px solid #f0f0f0;
            background-color: #ffffff;
        }

        .menu-toggle {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            color: #666;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            margin-right: 16px;
            transform: scale(1);
            will-change: transform, background-color, color;
        }

        .menu-toggle:hover {
            background-color: #f5f5f5;
            color: #333;
            transform: scale(1.1);
        }

        .menu-toggle:active {
            transform: scale(0.95);
        }

        /* 模型选择器 */
        .model-selector {
            margin-left: auto;
            margin-right: 16px;
            position: relative;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: transform, opacity;
        }
        
        .model-selector:hover {
            transform: scale(1.05);
        }
        
        .model-selector:focus-within {
            transform: scale(1.02);
        }

        /* 网络搜索按钮 */
        .search-button {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            color: #666;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            margin-right: 16px;
            position: relative;
            transform: scale(1);
            will-change: transform, background-color, color;
        }

        .search-button:hover {
            background-color: #f5f5f5;
            color: #333;
            transform: scale(1.1);
        }

        .search-button.active {
            background-color: #e3f2fd;
            color: #007bff;
            transform: scale(1.05);
        }

        .search-button:active {
            transform: scale(0.95);
        }

        .search-button img {
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }

        .search-button.active img {
            filter: brightness(1.2) drop-shadow(0 0 4px rgba(0, 123, 255, 0.3));
            transform: scale(1.1);
        }

        /* 动画样式 */
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }

        @keyframes slideOutRight {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(100%);
                opacity: 0;
            }
        }

        .model-selector select {
            padding: 6px 12px;
            border: 1px solid #e1e8ed;
            border-radius: 6px;
            background-color: #ffffff;
            color: #333;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            transform: scale(1);
            will-change: transform, border-color, background-color;
        }

        .model-selector select:hover {
            border-color: #007bff;
            background-color: #f8f9fa;
            transform: scale(1.02);
            box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
        }

        .model-selector select:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
            transform: scale(1.01);
        }
        
        /* 模型选择器下拉动画 */
        .model-selector select option {
            transition: all 0.2s ease;
            padding: 8px 12px;
        }
        
        .model-selector select option:hover {
            background-color: #e3f2fd;
            transform: translateX(4px);
        }

        .toolbar-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
            flex: 1;
        }

        /* 聊天容器 */
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            max-width: 100%;
            margin: 0 auto;
            width: 100%;
            padding: 0 20px;
            height: calc(100vh - 50px); /* 减少工具栏高度影响 */
        }

        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px 0;
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
            max-height: calc(100vh - 180px); /* 减少底部空间占用 */
            /* 隐藏滚动条但保持滚动能力 */
            scrollbar-width: none; /* Firefox */
            -ms-overflow-style: none; /* IE and Edge */
        }
        
        .messages-container::-webkit-scrollbar {
            display: none; /* Chrome, Safari and Opera */
        }

        .message {
            margin-bottom: 20px;
            display: flex;
            align-items: flex-start;
            animation: fadeIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: transform, opacity;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message.ai {
            justify-content: flex-start;
        }

        .message-bubble {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            line-height: 1.5;
            font-size: 15px;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: transform, background-color;
        }

        .message.user .message-bubble {
            background-color: #f0f7ff;
            color: #333;
            border: 1px solid #e1e8ed;
            transform: translateX(0);
        }

        .message.ai .message-bubble {
            background-color: #f8f9fa;
            color: #333;
            border: 1px solid #e9ecef;
            white-space: pre-wrap; /* 保留换行和空格 */
            word-wrap: break-word; /* 长单词换行 */
            line-height: 1.6; /* 增加行高提高可读性 */
            transform: translateX(0);
        }

        .message:hover .message-bubble {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        /* AI消息段落间距优化 */
        .message.ai .message-bubble p {
            margin: 0 0 8px 0; /* 段落间距 */
        }
        
        .message.ai .message-bubble p:last-child {
            margin-bottom: 0; /* 最后一个段落无下边距 */
        }
        
        .message.ai .message-bubble br {
            line-height: 1.4; /* 换行高度 */
        }

        /* 底部输入区域菜单按钮和菜单 */
        .input-container {
            display: flex;
            align-items: center;
            padding: 12px 0 8px 0;
            border-top: 1px solid #f0f0f0;
            background-color: #ffffff;
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
        }
        
        .input-menu-wrapper {
            position: relative;
            display: flex;
            align-items: center;
            margin-right: 10px;
        }
        
        .menu-button {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            color: #666;
            transition: all 0.2s ease;
        }
        
        .menu-button:hover {
            background-color: #f5f5f5;
            color: #333;
        }
        
        .voice-button {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 6px;
            color: #666;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            margin-right: 10px;
            transform: scale(1);
            will-change: transform, background-color, color;
        }
        
        .voice-button:hover {
            background-color: #f5f5f5;
            color: #333;
            transform: scale(1.1);
        }
        
        .voice-button.recording {
            background-color: #ff4444;
            color: white;
            animation: pulse 1.5s infinite cubic-bezier(0.25, 0.46, 0.45, 0.94);
            transform: scale(1.05);
        }
        
        .voice-button.recording img {
            filter: brightness(0) invert(1);
            transition: filter 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }

        .voice-button:active {
            transform: scale(0.95);
        }
        
        @keyframes pulse {
            0% {
                transform: scale(1);
            }
            50% {
                transform: scale(1.1);
            }
            100% {
                transform: scale(1);
            }
        }
        
        .input-menu {
            position: absolute;
            bottom: 50px; /* 菜单出现在按钮上方 */
            left: 0;
            background-color: #ffffff;
            border: 1px solid #e1e8ed;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
            z-index: 1000;
            min-width: 160px;
            padding: 6px 0;
            display: none; /* 默认隐藏 */
            flex-direction: column;
            transform: scale(0.8) translateY(20px);
            opacity: 0;
            transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: transform, opacity;
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        
        .input-menu.show {
            display: flex;
            transform: scale(1) translateY(0);
            opacity: 1;
            animation: menuSlideIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
        }
        
        @keyframes menuSlideIn {
            0% {
                transform: scale(0.8) translateY(20px);
                opacity: 0;
            }
            50% {
                transform: scale(1.02) translateY(-2px);
                opacity: 0.8;
            }
            100% {
                transform: scale(1) translateY(0);
                opacity: 1;
            }
        }
        
        .input-menu.hiding {
            animation: menuSlideOut 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
        }
        
        @keyframes menuSlideOut {
            0% {
                transform: scale(1) translateY(0);
                opacity: 1;
            }
            100% {
                transform: scale(0.8) translateY(20px);
                opacity: 0;
            }
        }
        
        .menu-item {
            background: none;
            border: none;
            padding: 10px 15px;
            text-align: left;
            cursor: pointer;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #333;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            width: 100%;
            border-radius: 6px;
            margin: 2px 0;
            transform: scale(1);
            will-change: transform, background-color, color;
        }
        
        .menu-item:hover {
            background-color: #f0f0f0;
            transform: scale(1.02);
        }
        
        .menu-item.active {
            background-color: #e3f2fd;
            color: #007bff;
            transform: scale(1.02);
        }
        
        .menu-item.active img {
            filter: brightness(1.2) drop-shadow(0 0 4px rgba(0, 123, 255, 0.3));
            transition: filter 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
        }

        .menu-item:active {
            transform: scale(0.98);
        }
        
        .menu-item img {
            margin-right: 8px;
            width: 20px;
            height: 20px;
        }

        .input-wrapper {
            display: flex;
            align-items: center;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 24px;
            padding: 12px 16px;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            flex: 1;
            will-change: border-color, background-color, box-shadow;
        }

        .input-wrapper:focus-within {
            border-color: #007bff;
            background-color: #ffffff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.1);
            transform: scale(1.005);
        }

        .message-input {
            flex: 1;
            border: none;
            outline: none;
            background: transparent;
            font-size: 15px;
            line-height: 1.5;
            resize: none;
            max-height: 120px;
            min-height: 20px;
            font-family: inherit;
            padding-top: 2px;
            padding-bottom: 2px;
        }

        .send-button {
            background: none;
            border: none;
            color: #007bff;
            cursor: pointer;
            padding: 8px;
            border-radius: 50%;
            transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            margin-left: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 36px;
            width: 36px;
            transform: scale(1);
            will-change: transform, background-color, color;
        }

        .send-button:hover {
            background-color: #e3f2fd;
            transform: scale(1.1);
        }

        .send-button:active {
            transform: scale(0.9);
        }

        .send-button:disabled {
            color: #ccc;
            cursor: not-allowed;
        }

        .send-button:disabled:hover {
            background: none;
        }

        .welcome-message {
            text-align: center;
            color: #666;
            font-size: 16px;
            margin: 40px 0;
        }

        .typing-indicator {
            display: none;
            padding: 12px 16px;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 18px;
            margin-bottom: 20px;
            width: fit-content;
            animation: fadeIn 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: opacity, transform;
        }

        .typing-indicator span {
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #999;
            margin: 0 2px;
            animation: typing 1.4s infinite cubic-bezier(0.25, 0.46, 0.45, 0.94);
            will-change: transform;
        }

        .typing-indicator span:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-indicator span:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-10px);
            }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                height: 100vh;
                box-shadow: 2px 0 8px rgba(0,0,0,0.1);
            }
            
            .main-content.expanded {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <!-- 侧边栏 -->
    <div class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <h2>历史对话</h2>
            <div class="header-buttons">
                <button class="delete-history-btn" onclick="deleteAllHistory()" title="删除所有历史对话">
                    <img src="icon\delete.png" width="16" height="16" alt="删除历史">
                </button>
                <button class="new-chat-btn" onclick="newChat()">新建对话</button>
            </div>
        </div>
        <div class="chat-history" id="chatHistory">
            <div class="chat-item active" onclick="selectChat(this)">
                当前对话
            </div>
        </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content" id="mainContent">
        <!-- 顶部工具栏 -->
        <div class="toolbar">
            <button class="menu-toggle" id="menuToggle" onclick="toggleSidebar()" title="切换侧边栏">
                <img src="iconic/Dark sidebar.png" width="20" height="20" alt="侧边栏" id="sidebarIcon">
            </button>
            
            <!-- 模型选择器 -->
            <div class="model-selector">
                <select id="modelSelect" onchange="changeModel()">
                    <option value="deepseek/deepseek-chat-v3.1:free">DeepSeek Chat</option>
                    <option value="z-ai/glm-4.5-air:free">GLM-4.5 Air</option>
                    <option value="Qwen/QwQ-32B">Qwen QwQ-32B</option>
                </select>
            </div>
        </div>

        <!-- 聊天容器 -->
        <div class="chat-container">
            <div class="messages-container" id="messagesContainer">
                <div class="welcome-message">
                    欢迎使用 AI 助手！有什么可以帮助您的吗？
                </div>
            </div>
            
            <div class="typing-indicator" id="typingIndicator">
                <span></span>
                <span></span>
                <span></span>
            </div>
            
            <div class="input-container">
                <div class="input-menu-wrapper">
                    <button class="menu-button" id="inputMenuButton" title="更多选项">
                        <img src="iconic/Dark new build.png" width="20" height="20" alt="菜单">
                    </button>
                    <div class="input-menu" id="inputMenu">
                        <button class="menu-item" id="searchMenuItem" onclick="toggleSearch()">
                            <img src="iconic/Dark web.png" width="20" height="20" alt="网络搜索">
                            <span>联网搜索</span>
                        </button>
                        <button class="menu-item" id="updateMenuItem" onclick="checkForUpdates()">
                            <img src="iconic/Dark color refresh.png" width="20" height="20" alt="检查更新">
                            <span>检查更新</span>
                        </button>
                    </div>
                </div>
                <button class="voice-button" id="voiceButton" title="语音输入">
                    <img src="iconic/Dark voice.png" width="20" height="20" alt="语音输入" id="voiceIcon">
                </button>
                <div class="input-wrapper">
                    <textarea 
                        class="message-input" 
                        id="messageInput" 
                        placeholder="输入您的问题..."
                        rows="1"
                    ></textarea>
                    <button class="send-button" id="sendButton" title="发送消息">
                        <img src="iconic\\深色发送.png" width="20" height="20" alt="发送" id="sendIcon">
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const messageInput = document.getElementById('messageInput');
        const sendButton = document.getElementById('sendButton');
        const messagesContainer = document.getElementById('messagesContainer');
        const typingIndicator = document.getElementById('typingIndicator');
        const sidebar = document.getElementById('sidebar');
        const mainContent = document.getElementById('mainContent');
        const menuToggle = document.getElementById('menuToggle');
        const inputMenuButton = document.getElementById('inputMenuButton');
        const inputMenu = document.getElementById('inputMenu');
        const voiceButton = document.getElementById('voiceButton');
        const voiceIcon = document.getElementById('voiceIcon');

        // 切换输入区域菜单的显示/隐藏（优化动画）
        inputMenuButton.addEventListener('click', function(event) {
            event.stopPropagation(); // 阻止事件冒泡
            
            if (inputMenu.classList.contains('show')) {
                // 关闭菜单动画
                inputMenu.classList.remove('show');
                inputMenu.classList.add('hiding');
                setTimeout(() => {
                    inputMenu.classList.remove('hiding');
                }, 300);
            } else {
                // 打开菜单动画
                inputMenu.classList.remove('hiding');
                inputMenu.classList.add('show');
            }
        });

        // 点击菜单外部时隐藏菜单（优化动画）
        document.addEventListener('click', function(event) {
            if (!inputMenu.contains(event.target) && !inputMenuButton.contains(event.target)) {
                if (inputMenu.classList.contains('show')) {
                    inputMenu.classList.remove('show');
                    inputMenu.classList.add('hiding');
                    setTimeout(() => {
                        inputMenu.classList.remove('hiding');
                    }, 300);
                }
            }
        });

        let isSidebarOpen = true;
        let currentChatId = 'current_chat';
        let chatHistories = {};

        // API 配置 - 支持多个API提供商
        const API_CONFIGS = {
            'deepseek/deepseek-chat-v3.1:free': {
                key: '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',
                url: 'https://openrouter.ai/api/v1/chat/completions',
                model: 'deepseek/deepseek-chat-v3.1:free'
            },

            'z-ai/glm-4.5-air:free': {
                key: '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',
                url: 'https://openrouter.ai/api/v1/chat/completions',
                model: 'z-ai/glm-4.5-air:free'
            },
            'Qwen/QwQ-32B': {
                key: 'sk-nizbjwzckbbgrnstgzijzusepjsvzgdjfgsfowcsuijsgwat',
                url: 'https://api.siliconflow.cn/v1/chat/completions',
                model: 'Qwen/QwQ-32B'
            }
        };

        // Tavily 搜索API配置
        const TAVILY_CONFIG = {
            apiKey: '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',
            url: 'https://api.tavily.com/search'
        };

        // 语音识别相关变量
        let isRecording = false;
        let mediaRecorder = null;
        let audioChunks = [];
        let silenceTimer = null;
        let audioContext = null;
        let analyser = null;
        let microphone = null;
        
        // 语音识别API配置
        const VOICE_API_CONFIG = {
            key: 'sk-nizbjwzckbbgrnstgzijzusepjsvzgdjfgsfowcsuijsgwat',
            url: 'https://api.siliconflow.cn/v1/audio/transcriptions',
            model: 'FunAudioLLM/SenseVoiceSmall'
        };
        
        // 搜索功能开关
        let isSearchEnabled = true; // 默认启用搜索功能

        // 切换搜索功能
        function toggleSearch() {
            isSearchEnabled = !isSearchEnabled;
            
            console.log('搜索功能已' + (isSearchEnabled ? '启用' : '禁用'));
            
            // 保存搜索开关状态到本地存储
            localStorage.setItem('searchEnabled', isSearchEnabled);
            
            // 更新按钮视觉状态
            updateSearchButtonState();
            
            // 显示状态提示
            showSearchStatusNotification(isSearchEnabled);
        }
        
        // 更新搜索按钮状态
        function updateSearchButtonState() {
            const searchMenuItem = document.getElementById('searchMenuItem');
            if (searchMenuItem) {
                if (isSearchEnabled) {
                    searchMenuItem.classList.add('active');
                } else {
                    searchMenuItem.classList.remove('active');
                }
            }
        }

        // 显示搜索状态提示
        function showSearchStatusNotification(enabled) {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${enabled ? '#28a745' : '#6c757d'};
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 10000;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                animation: slideInRight 0.3s ease;
            `;
            notification.textContent = enabled ? '✅ 网络搜索已启用' : '❌ 网络搜索已禁用';
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 2000);
        }
        
        // 显示语音识别状态提示
        function showVoiceStatusNotification(message, isSuccess = true) {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${isSuccess ? '#28a745' : '#dc3545'};
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 10000;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                animation: slideInRight 0.3s ease;
            `;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }

        // 自动更新功能配置 - 已配置Gitee仓库
        const UPDATE_CONFIG = {
            // 更新服务器类型：gitee | github | oss | cos | self-hosted
            serverType: 'gitee', // 使用Gitee，国内访问最佳
            
            // Gitee配置（您的仓库）
            giteeRepo: 'AI-SZK/ai',
            giteeVersionUrl: 'https://gitee.com/AI-SZK/ai/raw/main/version.json',
            giteeDownloadUrl: 'https://gitee.com/AI-SZK/ai/releases/download/v{version}/AI聊天助手-Setup-{version}.exe',
            
            // GitHub配置（备用，国际用户）
            githubRepo: 'AI-SZK/ai',
            githubVersionUrl: 'https://raw.githubusercontent.com/AI-SZK/ai/main/version.json',
            githubDownloadUrl: 'https://github.com/AI-SZK/ai/releases/download/v{version}/AI聊天助手-Setup-{version}.exe',
            
            // 云存储备用方案
            ossVersionUrl: 'https://your-bucket.oss-cn-hangzhou.aliyuncs.com/version.json',
            ossDownloadUrl: 'https://your-bucket.oss-cn-hangzhou.aliyuncs.com/releases/AI聊天助手-Setup-{version}.exe',
            
            cosVersionUrl: 'https://your-bucket.cos.ap-beijing.myqcloud.com/version.json',
            cosDownloadUrl: 'https://your-bucket.cos.ap-beijing.myqcloud.com/releases/AI聊天助手-Setup-{version}.exe',
            
            // 当前应用版本
            currentVersion: '1.0.0',
            // 自动检查更新间隔（7天）
            autoCheckInterval: 7 * 24 * 60 * 60 * 1000,
            // 是否启用自动检查
            enableAutoCheck: true
        };

        // 初始化自动更新功能
        function initAutoUpdate() {
            // 检查是否应该自动检查更新
            const lastCheckTime = localStorage.getItem('lastUpdateCheckTime');
            const currentTime = Date.now();
            
            if (UPDATE_CONFIG.enableAutoCheck && 
                (!lastCheckTime || currentTime - parseInt(lastCheckTime) > UPDATE_CONFIG.autoCheckInterval)) {
                
                console.log('自动检查更新...');
                checkForUpdates();
                
                // 更新最后检查时间
                localStorage.setItem('lastUpdateCheckTime', currentTime.toString());
            }
        }

        // 应用启动时初始化自动更新
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                initAutoUpdate();
            }, 3000); // 延迟3秒检查，避免影响启动体验
        });

        // 检查更新
        async function checkForUpdates() {
            console.log('开始检查更新...');
            
            // 显示检查中状态
            showUpdateNotification('🔍 正在检查更新...', 'info');
            
            try {
                // 获取最新版本信息
                const latestVersionInfo = await getLatestVersionInfo();
                
                if (!latestVersionInfo) {
                    showUpdateNotification('❌ 无法获取更新信息', 'error');
                    return;
                }
                
                // 比较版本
                const isUpdateAvailable = compareVersions(UPDATE_CONFIG.currentVersion, latestVersionInfo.version);
                
                if (isUpdateAvailable) {
                    // 有新版本可用
                    showUpdateDialog(latestVersionInfo);
                } else {
                    // 已是最新版本
                    showUpdateNotification('✅ 已是最新版本', 'success');
                }
                
            } catch (error) {
                console.error('检查更新失败:', error);
                showUpdateNotification('❌ 检查更新失败: ' + error.message, 'error');
            }
        }

        // 智能选择最佳更新源
        async function selectBestUpdateSource() {
            const sources = [
                {
                    name: 'local-test',
                    versionUrl: './version.json', // 本地测试
                    downloadUrl: '#', // 本地测试不实际下载
                    priority: 0 // 本地测试最高优先级
                },
                {
                    name: 'gitee',
                    versionUrl: UPDATE_CONFIG.giteeVersionUrl,
                    downloadUrl: UPDATE_CONFIG.giteeDownloadUrl,
                    priority: 1 // 国内用户首选
                },
                {
                    name: 'github', 
                    versionUrl: UPDATE_CONFIG.githubVersionUrl,
                    downloadUrl: UPDATE_CONFIG.githubDownloadUrl,
                    priority: 2 // 国际用户备用
                },
                {
                    name: 'oss',
                    versionUrl: UPDATE_CONFIG.ossVersionUrl,
                    downloadUrl: UPDATE_CONFIG.ossDownloadUrl,
                    priority: 3 // 云存储备用
                },
                {
                    name: 'cos',
                    versionUrl: UPDATE_CONFIG.cosVersionUrl,
                    downloadUrl: UPDATE_CONFIG.cosDownloadUrl,
                    priority: 4 // 云存储备用
                }
            ];
            
            // 按优先级排序
            sources.sort((a, b) => a.priority - b.priority);
            
            // 测试每个源的可用性
            for (const source of sources) {
                try {
                    console.log(`测试更新源: ${source.name}`);
                    const response = await fetch(source.versionUrl, {
                        method: 'HEAD',
                        headers: {
                            'Cache-Control': 'no-cache',
                            'User-Agent': 'AI-Chat-Assistant/' + UPDATE_CONFIG.currentVersion
                        }
                    });
                    
                    if (response.ok) {
                        console.log(`✅ 更新源 ${source.name} 可用`);
                        return source;
                    }
                } catch (error) {
                    console.warn(`❌ 更新源 ${source.name} 不可用:`, error.message);
                }
            }
            
            return null; // 所有源都不可用
        }

        // 获取最新版本信息
        async function getLatestVersionInfo() {
            try {
                // 智能选择最佳更新源
                const bestSource = await selectBestUpdateSource();
                
                if (!bestSource) {
                    throw new Error('所有更新源都不可用');
                }
                
                console.log(`使用更新源: ${bestSource.name}`);
                
                const response = await fetch(bestSource.versionUrl, {
                    method: 'GET',
                    headers: {
                        'Cache-Control': 'no-cache',
                        'User-Agent': 'AI-Chat-Assistant/' + UPDATE_CONFIG.currentVersion
                    }
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const versionInfo = await response.json();
                
                // 添加更新源信息
                versionInfo.updateSource = bestSource.name;
                versionInfo.downloadUrl = bestSource.downloadUrl.replace('{version}', versionInfo.version);
                
                return versionInfo;
                
            } catch (error) {
                console.error('获取版本信息失败:', error);
                return null;
            }
        }

        // 比较版本号
        function compareVersions(current, latest) {
            const currentParts = current.split('.').map(Number);
            const latestParts = latest.split('.').map(Number);
            
            for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {
                const currentPart = currentParts[i] || 0;
                const latestPart = latestParts[i] || 0;
                
                if (latestPart > currentPart) {
                    return true;
                } else if (latestPart < currentPart) {
                    return false;
                }
            }
            
            return false; // 版本相同
        }

        // 显示更新对话框
        function showUpdateDialog(versionInfo) {
            // 创建更新对话框
            const dialog = document.createElement('div');
            dialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border-radius: 12px;
                padding: 24px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                z-index: 10000;
                min-width: 400px;
                max-width: 500px;
                animation: dialogSlideIn 0.3s ease-out;
            `;
            
            dialog.innerHTML = `
                <div style="margin-bottom: 16px;">
                    <h3 style="margin: 0 0 8px 0; color: #333; font-size: 18px;">🎉 发现新版本</h3>
                    <p style="margin: 0; color: #666; font-size: 14px;">版本 ${versionInfo.version} 现已可用</p>
                </div>
                
                <div style="margin-bottom: 20px; padding: 12px; background: #f8f9fa; border-radius: 6px;">
                    <p style="margin: 0 0 8px 0; font-weight: bold; color: #333;">更新内容:</p>
                    <p style="margin: 0; color: #666; font-size: 13px; line-height: 1.4;">${versionInfo.description || '性能优化和功能改进'}</p>
                </div>
                
                <div style="display: flex; gap: 12px; justify-content: flex-end;">
                    <button id="updateLater" style="padding: 8px 16px; border: 1px solid #ddd; background: white; border-radius: 6px; color: #666; cursor: pointer;">稍后更新</button>
                    <button id="updateNow" style="padding: 8px 16px; border: none; background: #007bff; border-radius: 6px; color: white; cursor: pointer;">立即更新</button>
                </div>
            `;
            
            // 添加动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes dialogSlideIn {
                    from { opacity: 0; transform: translate(-50%, -60%); }
                    to { opacity: 1; transform: translate(-50%, -50%); }
                }
            `;
            document.head.appendChild(style);
            
            document.body.appendChild(dialog);
            
            // 添加背景遮罩
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.5);
                z-index: 9999;
            `;
            document.body.appendChild(overlay);
            
            // 事件处理
            document.getElementById('updateLater').onclick = function() {
                dialog.remove();
                overlay.remove();
                style.remove();
            };
            
            document.getElementById('updateNow').onclick = function() {
                startUpdateProcess(versionInfo);
                dialog.remove();
                overlay.remove();
                style.remove();
            };
        }

        // 开始更新过程
        async function startUpdateProcess(versionInfo) {
            console.log('开始下载更新...');
            
            // 显示下载进度
            const progressDialog = createProgressDialog();
            
            try {
                // 使用版本信息中存储的下载URL（来自智能选择的更新源）
                const downloadUrl = versionInfo.downloadUrl;
                
                console.log(`使用下载源: ${versionInfo.updateSource}, URL: ${downloadUrl}`);
                
                // 如果是本地测试模式，模拟下载过程
                if (versionInfo.updateSource === 'local-test') {
                    console.log('本地测试模式：模拟下载过程');
                    
                    // 模拟下载进度
                    for (let i = 0; i <= 100; i += 10) {
                        await new Promise(resolve => setTimeout(resolve, 200));
                        updateProgressDialog(progressDialog, {
                            loaded: i * 1024 * 1024, // 模拟文件大小
                            total: 100 * 1024 * 1024,
                            percentage: i
                        });
                    }
                    
                    // 下载完成，提示用户安装
                    progressDialog.innerHTML = `
                        <div style="text-align: center; padding: 20px;">
                            <h3 style="color: #28a745; margin-bottom: 16px;">✅ 本地测试完成</h3>
                            <p style="margin-bottom: 20px;">自动更新功能测试成功！在实际环境中，更新文件将从 ${versionInfo.updateSource} 下载。</p>
                            <p style="color: #666; font-size: 12px;">提示：请确保已将version.json文件上传到Gitee仓库</p>
                            <button id="installUpdate" style="padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 6px; cursor: pointer;">测试完成</button>
                        </div>
                    `;
                    
                    document.getElementById('installUpdate').onclick = function() {
                        progressDialog.remove();
                    };
                } else {
                    // 实际下载更新文件
                    await downloadUpdateFile(downloadUrl, (progress) => {
                        updateProgressDialog(progressDialog, progress);
                    });
                    
                    // 下载完成，提示用户安装
                    progressDialog.innerHTML = `
                        <div style="text-align: center; padding: 20px;">
                            <h3 style="color: #28a745; margin-bottom: 16px;">✅ 下载完成</h3>
                            <p style="margin-bottom: 20px;">更新文件已从 ${versionInfo.updateSource} 下载完成，点击"立即安装"开始安装新版本。</p>
                            <button id="installUpdate" style="padding: 10px 20px; background: #28a745; color: white; border: none; border-radius: 6px; cursor: pointer;">立即安装</button>
                        </div>
                    `;
                    
                    document.getElementById('installUpdate').onclick = function() {
                        // 执行安装程序
                        installUpdate(versionInfo);
                    };
                }
                
            } catch (error) {
                console.error('更新失败:', error);
                progressDialog.innerHTML = `
                    <div style="text-align: center; padding: 20px; color: #dc3545;">
                        <h3>❌ 更新失败</h3>
                        <p>从 ${versionInfo.updateSource} 下载失败: ${error.message}</p>
                        <p style="color: #666; font-size: 12px;">请检查网络连接或仓库设置</p>
                        <button onclick="this.parentElement.parentElement.remove()" style="padding: 8px 16px; background: #dc3545; color: white; border: none; border-radius: 6px; cursor: pointer;">关闭</button>
                    </div>
                `;
            }
        }

        // 创建进度对话框
        function createProgressDialog() {
            const dialog = document.createElement('div');
            dialog.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                border-radius: 12px;
                padding: 24px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                z-index: 10001;
                min-width: 300px;
                text-align: center;
            `;
            
            dialog.innerHTML = `
                <h3 style="margin: 0 0 16px 0; color: #333;">📥 正在下载更新</h3>
                <div style="background: #f0f0f0; border-radius: 10px; height: 20px; margin-bottom: 16px; overflow: hidden;">
                    <div id="progressBar" style="background: #007bff; height: 100%; width: 0%; transition: width 0.3s ease;"></div>
                </div>
                <p id="progressText" style="margin: 0; color: #666;">准备下载...</p>
            `;
            
            document.body.appendChild(dialog);
            return dialog;
        }

        // 更新进度对话框
        function updateProgressDialog(dialog, progress) {
            const progressBar = dialog.querySelector('#progressBar');
            const progressText = dialog.querySelector('#progressText');
            
            if (progressBar) {
                progressBar.style.width = progress.percentage + '%';
            }
            
            if (progressText) {
                progressText.textContent = `已下载 ${Math.round(progress.loaded / 1024 / 1024)}MB / ${Math.round(progress.total / 1024 / 1024)}MB`;
            }
        }

        // 下载更新文件
        async function downloadUpdateFile(url, progressCallback) {
            return new Promise((resolve, reject) => {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', url, true);
                xhr.responseType = 'blob';
                
                xhr.onprogress = function(event) {
                    if (event.lengthComputable) {
                        const percentage = (event.loaded / event.total) * 100;
                        progressCallback({
                            loaded: event.loaded,
                            total: event.total,
                            percentage: percentage
                        });
                    }
                };
                
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        const blob = xhr.response;
                        const downloadUrl = window.URL.createObjectURL(blob);
                        
                        // 保存下载的文件（在实际应用中需要更复杂的文件处理）
                        const a = document.createElement('a');
                        a.href = downloadUrl;
                        a.download = `AI聊天助手-Setup-${UPDATE_CONFIG.currentVersion}.exe`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                        
                        window.URL.revokeObjectURL(downloadUrl);
                        resolve();
                    } else {
                        reject(new Error(`下载失败: HTTP ${xhr.status}`));
                    }
                };
                
                xhr.onerror = function() {
                    reject(new Error('网络错误，下载失败'));
                };
                
                xhr.send();
            });
        }

        // 安装更新
        function installUpdate(versionInfo) {
            // 在实际应用中，这里会执行下载的安装程序
            // 由于安全限制，浏览器中无法直接执行exe文件
            // 这里显示提示信息
            
            showUpdateNotification('🔧 请运行下载的安装程序完成更新', 'info');
            
            // 在实际的Electron应用中，可以使用shell.openExternal或child_process执行安装程序
            console.log('开始安装更新:', versionInfo.version);
        }

        // 显示更新通知
        function showUpdateNotification(message, type = 'info') {
            const notification = document.createElement('div');
            const bgColor = type === 'error' ? '#dc3545' : 
                           type === 'success' ? '#28a745' : 
                           type === 'warning' ? '#ffc107' : '#007bff';
            
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: ${bgColor};
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 10000;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                animation: slideInRight 0.3s ease;
            `;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.style.animation = 'slideOutRight 0.3s ease';
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, type === 'error' ? 5000 : 3000);
        }
        
        let CURRENT_API_CONFIG = API_CONFIGS['deepseek/deepseek-chat-v3.1:free']; // 默认配置
        let MODEL_NAME = CURRENT_API_CONFIG.model; // 默认模型
        
        // 语音识别功能
        async function startVoiceRecording() {
            try {
                // 检查浏览器是否支持录音
                if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
                    showVoiceStatusNotification('❌ 您的浏览器不支持语音录制', false);
                    return;
                }
                
                // 请求麦克风权限
                const stream = await navigator.mediaDevices.getUserMedia({ 
                    audio: {
                        sampleRate: 16000,
                        channelCount: 1,
                        echoCancellation: true,
                        noiseSuppression: true
                    } 
                });
                
                // 创建媒体录制器
                mediaRecorder = new MediaRecorder(stream, {
                    mimeType: 'audio/webm;codecs=opus'
                });
                
                audioChunks = [];
                
                // 录制数据可用时的处理
                mediaRecorder.ondataavailable = (event) => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                    }
                };
                
                // 录制结束时的处理
                mediaRecorder.onstop = async () => {
                    // 停止所有音轨
                    stream.getTracks().forEach(track => track.stop());
                    
                    // 停止静音检测
                    stopSilenceDetection();
                    
                    // 处理录制的音频
                    await processRecordedAudio();
                };
                
                // 开始录制
                mediaRecorder.start(1000); // 每1秒收集一次数据
                isRecording = true;
                
                // 启动静音检测
                startSilenceDetection(stream);
                
                // 更新按钮状态
                voiceButton.classList.add('recording');
                voiceIcon.src = 'iconic/Light-colored voice.png';
                
                showVoiceStatusNotification('🎤 正在录音...', true);
                
            } catch (error) {
                console.error('语音录制启动失败:', error);
                showVoiceStatusNotification('❌ 无法访问麦克风', false);
            }
        }
        
        function stopVoiceRecording() {
            if (mediaRecorder && isRecording) {
                mediaRecorder.stop();
                isRecording = false;
                
                // 停止静音检测
                stopSilenceDetection();
                
                // 更新按钮状态
                voiceButton.classList.remove('recording');
                voiceIcon.src = 'iconic/Dark voice.png';
                
                showVoiceStatusNotification('⏹️ 录音结束，正在识别...', true);
            }
        }
        
        // 启动静音检测
        function startSilenceDetection(stream) {
            try {
                // 创建音频上下文
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
                analyser = audioContext.createAnalyser();
                microphone = audioContext.createMediaStreamSource(stream);
                
                // 配置分析器
                analyser.fftSize = 256;
                analyser.smoothingTimeConstant = 0.8;
                
                // 连接音频节点
                microphone.connect(analyser);
                
                // 开始检测静音
                detectSilence();
                
            } catch (error) {
                console.warn('静音检测初始化失败:', error);
                // 如果静音检测失败，使用备用方案：5秒后自动停止
                silenceTimer = setTimeout(() => {
                    if (isRecording) {
                        showVoiceStatusNotification('⏰ 长时间静音，自动结束录音', true);
                        stopVoiceRecording();
                    }
                }, 5000);
            }
        }
        
        // 停止静音检测
        function stopSilenceDetection() {
            if (silenceTimer) {
                clearTimeout(silenceTimer);
                silenceTimer = null;
            }
            
            if (audioContext) {
                audioContext.close();
                audioContext = null;
            }
            
            analyser = null;
            microphone = null;
        }
        
        // 检测静音
        function detectSilence() {
            if (!isRecording || !analyser) return;
            
            const bufferLength = analyser.frequencyBinCount;
            const dataArray = new Uint8Array(bufferLength);
            analyser.getByteFrequencyData(dataArray);
            
            // 计算音量（平均值）
            let sum = 0;
            for (let i = 0; i < bufferLength; i++) {
                sum += dataArray[i];
            }
            const average = sum / bufferLength;
            
            // 音量阈值（可根据环境调整）
            const silenceThreshold = 10;
            
            if (average < silenceThreshold) {
                // 检测到静音
                if (!silenceTimer) {
                    // 开始2秒倒计时
                    silenceTimer = setTimeout(() => {
                        if (isRecording) {
                            showVoiceStatusNotification('🎯 检测到静音，自动结束录音', true);
                            stopVoiceRecording();
                        }
                    }, 2000);
                }
            } else {
                // 有声音，重置计时器
                if (silenceTimer) {
                    clearTimeout(silenceTimer);
                    silenceTimer = null;
                }
            }
            
            // 继续检测
            requestAnimationFrame(detectSilence);
        }
        
        async function processRecordedAudio() {
            try {
                if (audioChunks.length === 0) {
                    showVoiceStatusNotification('❌ 没有录制到音频', false);
                    return;
                }
                
                // 合并音频数据
                const audioBlob = new Blob(audioChunks, { type: 'audio/webm;codecs=opus' });
                
                // 调用语音识别API
                const transcribedText = await transcribeAudio(audioBlob);
                
                if (transcribedText) {
                    // 将识别结果填入输入框
                    messageInput.value = transcribedText;
                    // 自动调整输入框高度
                    messageInput.style.height = 'auto';
                    messageInput.style.height = messageInput.scrollHeight + 'px';
                    
                    showVoiceStatusNotification('✅ 语音识别成功', true);
                }
                
            } catch (error) {
                console.error('音频处理失败:', error);
                showVoiceStatusNotification('❌ 语音识别失败', false);
            }
        }
        
        async function transcribeAudio(audioBlob) {
            try {
                // 创建FormData
                const formData = new FormData();
                formData.append('model', VOICE_API_CONFIG.model);
                formData.append('file', audioBlob, 'recording.webm');
                
                // 调用语音识别API
                const response = await fetch(VOICE_API_CONFIG.url, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${VOICE_API_CONFIG.key}`
                    },
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status}`);
                }
                
                const data = await response.json();
                
                // 根据API响应格式提取文本
                if (data.text) {
                    return data.text;
                } else if (data.transcription) {
                    return data.transcription;
                } else {
                    throw new Error('API响应格式不匹配');
                }
                
            } catch (error) {
                console.error('语音识别API调用失败:', error);
                throw error;
            }
        }
        
        // 语音按钮点击事件
        voiceButton.addEventListener('click', function() {
            if (isRecording) {
                stopVoiceRecording();
            } else {
                startVoiceRecording();
            }
        });

        // 初始化时加载保存的对话历史
        function loadChatHistories() {
            const saved = localStorage.getItem('chatHistories');
            if (saved) {
                chatHistories = JSON.parse(saved);
                updateSidebar();
            }
        }

        // 检查网络连接状态
        async function checkNetworkStatus() {
            try {
                // 尝试访问一个可靠的测试地址
                const response = await fetch('https://www.google.com/generate_204', {
                    method: 'HEAD',
                    timeout: 5000
                });
                return response.ok;
            } catch (error) {
                console.warn('网络连接检查失败:', error);
                return false;
            }
        }

        // Tavily搜索功能
        async function searchWithTavily(query, maxResults = 5) {
            if (!isSearchEnabled) {
                return null;
            }

            try {
                console.log('正在使用Tavily搜索:', query);
                
                const response = await fetch(TAVILY_CONFIG.url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${TAVILY_CONFIG.apiKey}`
                    },
                    body: JSON.stringify({
                        query: query,
                        maxResults: maxResults,
                        includeImages: true,
                        includeImageDescriptions: true,
                        includeFavicon: true,
                        searchDepth: 'basic'
                    })
                });

                if (!response.ok) {
                    console.warn('Tavily搜索失败:', response.status, response.statusText);
                    return null;
                }

                const data = await response.json();
                console.log('Tavily搜索结果:', data);
                
                return data;
            } catch (error) {
                console.error('Tavily搜索错误:', error);
                return null;
            }
        }

        // 格式化搜索结果为AI可用的上下文
        function formatSearchResults(searchData) {
            if (!searchData || !searchData.results) {
                return '';
            }

            let formattedResults = '以下是基于网络搜索的最新信息：\n\n';
            
            searchData.results.forEach((result, index) => {
                formattedResults += `${index + 1}. **${result.title}**\n`;
                formattedResults += `   来源: ${result.url}\n`;
                formattedResults += `   内容: ${result.content}\n`;
                
                if (result.image) {
                    formattedResults += `   图片: ${result.image}\n`;
                }
                
                formattedResults += '\n';
            });

            return formattedResults;
        }

        // 切换模型（优化动画效果）
        function changeModel() {
            const modelSelect = document.getElementById('modelSelect');
            const selectedValue = modelSelect.value;
            
            // 添加模型切换动画
            modelSelect.style.transform = 'scale(0.95)';
            modelSelect.style.transition = 'transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)';
            
            setTimeout(() => {
                // 更新当前API配置
                CURRENT_API_CONFIG = API_CONFIGS[selectedValue];
                MODEL_NAME = CURRENT_API_CONFIG.model;
                
                console.log('已切换到模型:', MODEL_NAME);
                console.log('API配置:', CURRENT_API_CONFIG.url);
                
                // 保存当前选择的模型到本地存储
                localStorage.setItem('selectedModel', selectedValue);
                
                // 显示切换提示
                showModelChangeNotification(modelSelect.options[modelSelect.selectedIndex].text);
                
                // 恢复动画
                modelSelect.style.transform = 'scale(1)';
                
                // 检查网络连接
                checkNetworkStatus().then(isOnline => {
                    if (!isOnline) {
                        addMessage('⚠️ 网络连接可能存在问题，请检查网络设置', 'ai');
                    }
                });
            }, 150);
        }

        // 显示模型切换提示
        function showModelChangeNotification(modelName) {
            // 创建提示元素
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #007bff;
                color: white;
                padding: 12px 16px;
                border-radius: 6px;
                font-size: 14px;
                z-index: 1000;
                animation: slideIn 0.3s ease-out;
            `;
            notification.textContent = `已切换到 ${modelName} 模型`;
            
            // 添加动画样式
            const style = document.createElement('style');
            style.textContent = `
                @keyframes slideIn {
                    from { transform: translateX(100%); opacity: 0; }
                    to { transform: translateX(0); opacity: 1; }
                }
            `;
            document.head.appendChild(style);
            
            document.body.appendChild(notification);
            
            // 3秒后移除提示
            setTimeout(() => {
                notification.remove();
                style.remove();
            }, 3000);
        }

        // 保存对话历史到本地存储
        function saveChatHistories() {
            localStorage.setItem('chatHistories', JSON.stringify(chatHistories));
        }

        // 更新侧边栏显示
        function updateSidebar() {
            const chatHistory = document.getElementById('chatHistory');
            chatHistory.innerHTML = '';
            
            // 添加所有保存的对话
            Object.keys(chatHistories).forEach(chatId => {
                const chatItem = document.createElement('div');
                chatItem.className = 'chat-item';
                chatItem.textContent = chatHistories[chatId].title;
                chatItem.onclick = function() { selectChat(chatId); };
                if (chatId === currentChatId) {
                    chatItem.classList.add('active');
                }
                chatHistory.appendChild(chatItem);
            });
        }

        // 获取当前对话的消息
        function getCurrentMessages() {
            const messages = [];
            const messageElements = messagesContainer.querySelectorAll('.message');
            messageElements.forEach(msg => {
                const sender = msg.classList.contains('user') ? 'user' : 'ai';
                const content = msg.querySelector('.message-bubble').textContent;
                messages.push({ sender, content });
            });
            return messages;
        }

        // 保存当前对话
        function saveCurrentChat() {
            const messages = getCurrentMessages();
            if (messages.length > 0) {
                const title = messages[0].content.substring(0, 30) + (messages[0].content.length > 30 ? '...' : '');
                chatHistories[currentChatId] = {
                    title: title,
                    messages: messages,
                    timestamp: new Date().toISOString()
                };
                saveChatHistories();
                updateSidebar();
            }
        }

        // 切换侧边栏
        function toggleSidebar() {
            isSidebarOpen = !isSidebarOpen;
            if (isSidebarOpen) {
                sidebar.classList.remove('collapsed');
                mainContent.classList.remove('expanded');
            } else {
                sidebar.classList.add('collapsed');
                mainContent.classList.add('expanded');
            }
        }

        // 新建对话
        function newChat() {
            // 保存当前对话
            saveCurrentChat();
            
            // 生成新的对话ID
            currentChatId = 'chat_' + Date.now();
            
            // 清空当前对话
            messagesContainer.innerHTML = '<div class="welcome-message">欢迎使用 AI 助手！有什么可以帮助您的吗？</div>';
            
            // 更新侧边栏
            updateSidebar();
        }

        // 选择对话
        function selectChat(chatId) {
            // 保存当前对话
            saveCurrentChat();
            
            // 切换到新对话
            currentChatId = chatId;
            
            // 加载选中的对话历史
            if (chatHistories[chatId]) {
                messagesContainer.innerHTML = '';
                chatHistories[chatId].messages.forEach(msg => {
                    addMessage(msg.content, msg.sender);
                });
            } else {
                messagesContainer.innerHTML = '<div class="welcome-message">欢迎使用 AI 助手！有什么可以帮助您的吗？</div>';
            }
            
            // 更新侧边栏
            updateSidebar();
        }

        // 删除所有历史对话
        function deleteAllHistory() {
            if (confirm('确定要删除所有历史对话吗？此操作无法撤销。')) {
                // 清空对话历史
                chatHistories = {};
                
                // 保存到本地存储
                saveChatHistories();
                
                // 重置当前对话
                currentChatId = 'current_chat';
                messagesContainer.innerHTML = '<div class="welcome-message">欢迎使用 AI 助手！有什么可以帮助您的吗？</div>';
                
                // 更新侧边栏
                updateSidebar();
                
                console.log('所有历史对话已删除');
            }
        }

        // 自动调整输入框高度
        messageInput.addEventListener('input', function() {
            this.style.height = 'auto';
            this.style.height = Math.min(this.scrollHeight, 120) + 'px';
        });

        // 发送消息
        async function sendMessage() {
            const message = messageInput.value.trim();
            if (message === '') return;

            // 添加用户消息
            addMessage(message, 'user');
            messageInput.value = '';
            messageInput.style.height = 'auto';
            
            // 禁用发送按钮并显示加载状态
            sendButton.disabled = true;
            sendButton.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="12" r="2"><animate attributeName="r" values="2;4;2" dur="1.5s" repeatCount="indefinite"/></circle><circle cx="12" cy="12" r="2" transform="rotate(45 12 12)"><animate attributeName="r" values="2;4;2" dur="1.5s" repeatCount="indefinite"/></circle><circle cx="12" cy="12" r="2" transform="rotate(90 12 12)"><animate attributeName="r" values="2;4;2" dur="1.5s" repeatCount="indefinite"/></circle><circle cx="12" cy="12" r="2" transform="rotate(135 12 12)"><animate attributeName="r" values="2;4;2" dur="1.5s" repeatCount="indefinite"/></circle></svg>';
            
            // 保存当前fetch控制器，用于打断对话
            let controller = new AbortController();
            window.currentController = controller;
            
            // 将发送按钮变为打断按钮
            setTimeout(() => {
                if (sendButton.disabled) {
                    sendButton.innerHTML = '<img src="iconic/Dark color termination.png" width="20" height="20" alt="打断对话" id="breakIcon">';
                    sendButton.title = '打断对话';
                    sendButton.onclick = breakConversation;
                    sendButton.disabled = false;
                }
            }, 1000);
            
            try {
                // 获取当前对话历史，构建消息数组
                const messages = getCurrentMessages();
                let apiMessages = messages.map(msg => ({
                    role: msg.sender === 'user' ? 'user' : 'assistant',
                    content: msg.content
                }));

                // 对用户最新消息进行搜索（如果启用搜索功能）
                let searchContext = '';
                if (isSearchEnabled && messages.length > 0 && messages[messages.length - 1].sender === 'user') {
                    const userQuery = messages[messages.length - 1].content;
                    
                    // 判断是否需要搜索（简单的关键词判断）
                    const searchKeywords = ['今天', '最新', '最近', '新闻', '实时', '当前', '现在', '今日'];
                    const needsSearch = searchKeywords.some(keyword => userQuery.includes(keyword));
                    
                    if (needsSearch) {
                        console.log('检测到可能需要实时信息的关键词，正在搜索...');
                        const searchResults = await searchWithTavily(userQuery, 3);
                        
                        if (searchResults) {
                            searchContext = formatSearchResults(searchResults);
                            console.log('搜索结果已获取并格式化');
                        }
                    }
                }

                // 如果有搜索结果，添加到消息中
                if (searchContext) {
                    // 在系统消息中添加搜索上下文
                    apiMessages.unshift({
                        role: 'system',
                        content: `你是一个AI助手。${searchContext}请基于以上信息回答用户的问题。如果搜索结果与用户问题不相关，请忽略这些信息。`
                    });
                }
                
                // 创建流式消息元素
                const streamingBubble = createStreamingMessage();
                let fullContent = '';
                
                // 设置请求超时（30秒）
                const timeoutPromise = new Promise((_, reject) => {
                    setTimeout(() => reject(new Error('Request timeout')), 30000);
                });
                
                // 调用 API 支持流式输出
                const fetchPromise = fetch(CURRENT_API_CONFIG.url, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${CURRENT_API_CONFIG.key}`,
                        'Content-Type': 'application/json',
                        'HTTP-Referer': window.location.href,
                        'X-Title': 'AI Chat Assistant'
                    },
                    body: JSON.stringify({
                        model: CURRENT_API_CONFIG.model,
                        messages: apiMessages,
                        stream: true  // 启用流式输出
                    }),
                    signal: controller.signal  // 添加中断信号
                });
                
                // 使用 Promise.race 实现超时控制
                const response = await Promise.race([fetchPromise, timeoutPromise]);
                
                if (!response.ok) {
                    throw new Error(`API 请求失败: ${response.status} ${response.statusText}`);
                }
                
                // 处理流式响应（优化版）
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                
                // 优化流式输出性能
                let buffer = '';
                let lastUpdateTime = 0;
                const updateInterval = 50; // 50ms更新间隔，平衡流畅性和性能
                
                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;
                    
                    buffer += decoder.decode(value, { stream: true });
                    const lines = buffer.split('\n');
                    buffer = lines.pop() || ''; // 保留未完成的行
                    
                    const currentTime = Date.now();
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            if (data === '[DONE]') continue;
                            
                            try {
                                const parsed = JSON.parse(data);
                                if (parsed.choices && parsed.choices[0] && parsed.choices[0].delta) {
                                    const delta = parsed.choices[0].delta;
                                    if (delta.content) {
                                        fullContent += delta.content;
                                        
                                        // 优化更新频率，避免过度渲染
                                        if (currentTime - lastUpdateTime >= updateInterval) {
                                            updateStreamingMessage(streamingBubble, fullContent);
                                            lastUpdateTime = currentTime;
                                            
                                            // 使用requestAnimationFrame优化动画性能
                                            await new Promise(resolve => requestAnimationFrame(resolve));
                                        }
                                    }
                                }
                            } catch (e) {
                                console.warn('解析流式数据失败:', e);
                            }
                        }
                    }
                }
                
                // 确保最后的内容被更新
                if (fullContent) {
                    updateStreamingMessage(streamingBubble, fullContent);
                }
                
                // 流式输出完成后，保存对话
                if (fullContent) {
                    saveCurrentChat();
                }
                
            } catch (error) {
                // 如果是用户主动打断，不显示错误消息
                if (error.name === 'AbortError' || error.message.includes('aborted')) {
                    console.log('对话被用户打断');
                } else {
                    // 详细的错误处理和用户友好的提示
                    let errorMessage = '抱歉，出现了网络错误';
                    
                    if (error.message.includes('Failed to fetch')) {
                        errorMessage = '网络连接失败，请检查：\n1. 网络连接是否正常\n2. API服务是否可用\n3. 防火墙或代理设置';
                    } else if (error.message.includes('CORS')) {
                        errorMessage = '跨域请求被阻止，请检查API配置';
                    } else if (error.message.includes('timeout')) {
                        errorMessage = '请求超时，请稍后重试';
                    } else if (error.message.includes('401')) {
                        errorMessage = 'API密钥无效或已过期';
                    } else if (error.message.includes('429')) {
                        errorMessage = '请求过于频繁，请稍后再试';
                    } else if (error.message.includes('500')) {
                        errorMessage = '服务器内部错误，请稍后重试';
                    }
                    
                    // 显示错误消息
                    addMessage(errorMessage, 'ai');
                    
                    // 详细的控制台日志
                    console.error('=== API 调用错误详情 ===');
                    console.error('错误类型:', error.name);
                    console.error('错误消息:', error.message);
                    console.error('当前API配置:', CURRENT_API_CONFIG);
                    console.error('请求URL:', CURRENT_API_CONFIG.url);
                    console.error('请求模型:', CURRENT_API_CONFIG.model);
                    console.error('时间:', new Date().toLocaleString());
                    console.error('========================');
                }
            } finally {
                // 重新启用发送按钮并恢复原始图标
                sendButton.disabled = false;
                sendButton.innerHTML = '<img src="iconic\\深色发送.png" width="20" height="20" alt="发送" id="sendIcon">';
                sendButton.title = '发送消息';
                sendButton.onclick = sendMessage;
                messageInput.focus();
                
                // 清理控制器
                window.currentController = null;
            }
        }

        // 打断对话
        function breakConversation() {
            if (window.currentController) {
                window.currentController.abort();
                console.log('对话已打断');
                
                // 立即恢复发送按钮
                sendButton.disabled = false;
                sendButton.innerHTML = '<img src="iconic\\深色发送.png" width="20" height="20" alt="发送" id="sendIcon">';
                sendButton.title = '发送消息';
                sendButton.onclick = sendMessage;
                
                // 清理控制器
                window.currentController = null;
                
                // 添加打断提示消息
                addMessage('对话已被打断', 'ai');
            }
        }

        // 添加消息到对话（带内容清理）
        function addMessage(content, sender) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender}`;
            
            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = 'message-bubble';
            
            // 如果是AI消息，进行内容清理
            if (sender === 'ai') {
                bubbleDiv.textContent = cleanAIContent(content);
            } else {
                bubbleDiv.textContent = content;
            }
            
            messageDiv.appendChild(bubbleDiv);
            messagesContainer.appendChild(messageDiv);
            
            // 移除欢迎消息
            const welcomeMessage = messagesContainer.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.remove();
            }
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            // 自动保存对话
            saveCurrentChat();
        }

        // 显示输入指示器
        function showTypingIndicator() {
            typingIndicator.style.display = 'block';
            messagesContainer.appendChild(typingIndicator);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
        }

        // 隐藏输入指示器
        function hideTypingIndicator() {
            typingIndicator.style.display = 'none';
        }

        // 创建流式消息元素
        function createStreamingMessage() {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ai';
            
            const bubbleDiv = document.createElement('div');
            bubbleDiv.className = 'message-bubble';
            bubbleDiv.textContent = '正在思考中...';
            
            messageDiv.appendChild(bubbleDiv);
            messagesContainer.appendChild(messageDiv);
            
            // 移除欢迎消息
            const welcomeMessage = messagesContainer.querySelector('.welcome-message');
            if (welcomeMessage) {
                welcomeMessage.remove();
            }
            
            // 滚动到底部
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            return bubbleDiv;
        }

        // 清理AI回复内容
        function cleanAIContent(content) {
            // 清理无用的特殊符号（#*&等），但保留有用的标点符号
            content = content.replace(/[#*&]{2,}/g, ''); // 清理连续的特殊符号
            content = content.replace(/^[#*&\s]+|[#*&\s]+$/g, ''); // 清理开头和结尾的杂乱符号
            
            // 处理段落分隔 - 检测自然段落结束
            content = content.replace(/([。！？.!?]\s*)\n\s*\n/g, '$1\n'); // 移除段落间多余的空行
            content = content.replace(/([。！？.!?])\s*([A-Za-z一-龥])/g, '$1\n$2'); // 句子结束后添加单换行（不是双换行）
            
            // 处理列表格式 - 更合理的换行
            // 1. 处理数字序号（1. 2. 3. 等）
            content = content.replace(/(\d+)[\.\、]\s+/g, '\n$1. '); // 数字序号前加单换行
            
            // 2. 处理中文数字序号（一、二、三、等）
            content = content.replace(/([一二三四五六七八九十]+)[\.\、]\s+/g, '\n$1. ');
            
            // 3. 处理字母序号（A. B. C. 等）
            content = content.replace(/([A-Za-z])[\.\、]\s+/g, '\n$1. ');
            
            // 4. 处理项目符号（•、-、* 等）
            content = content.replace(/([•\-\*])\s+/g, '\n$1 ');
            
            // 处理代码块和特殊格式
            content = content.replace(/```([\s\S]*?)```/g, function(match, code) {
                return '\n```' + code.trim() + '\n```\n';
            });
            
            // 限制连续换行最多为2个（允许段落间有一个空行）
            content = content.replace(/\n{3,}/g, '\n\n');
            
            // 清理多余的空白字符，但保留段落间的换行
            content = content.replace(/[^\S\n]+/g, ' '); // 多个空格合并为一个，但不影响换行
            content = content.replace(/\n\s+\n/g, '\n\n'); // 清理空行中的多余空格
            content = content.trim(); // 清理首尾空白
            
            return content;
        }

        // 更新流式消息内容（优化版）
        function updateStreamingMessage(bubbleElement, content) {
            const cleanedContent = cleanAIContent(content);
            
            // 使用requestAnimationFrame优化动画性能
            requestAnimationFrame(() => {
                bubbleElement.textContent = cleanedContent;
                
                // 平滑滚动到底部
                messagesContainer.scrollTo({
                    top: messagesContainer.scrollHeight,
                    behavior: 'smooth'
                });
            });
        }

        // 事件监听
        sendButton.addEventListener('click', sendMessage);
        
        messageInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 聚焦输入框
        messageInput.focus();

        // 页面加载时初始化
        loadChatHistories();
        
        // 加载保存的模型选择
        function loadSavedModel() {
            const savedModel = localStorage.getItem('selectedModel');
            if (savedModel && API_CONFIGS[savedModel]) {
                CURRENT_API_CONFIG = API_CONFIGS[savedModel];
                MODEL_NAME = CURRENT_API_CONFIG.model;
                document.getElementById('modelSelect').value = savedModel;
                console.log('已加载保存的模型:', MODEL_NAME);
                console.log('API配置:', CURRENT_API_CONFIG.url);
            }
        }
        
        // 初始化模型选择
        loadSavedModel();
        
        // 初始化搜索开关状态
        function initializeSearchToggle() {
            const savedSearchState = localStorage.getItem('searchEnabled');
            
            if (savedSearchState !== null) {
                isSearchEnabled = savedSearchState === 'true';
            } else {
                // 默认启用搜索
                isSearchEnabled = true;
            }
            
            console.log('搜索功能初始化状态:', isSearchEnabled ? '启用' : '禁用');
            
            // 初始化按钮视觉状态
            updateSearchButtonState();
        }
        
        // 初始化搜索开关
        initializeSearchToggle();
    </script>
</body>
</html>